package com.qianfeng.smartdevice.events.listeners;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.qianfeng.smartdevice.events.UserLoginFailEvent;
import com.qianfeng.smartdevice.events.UserLoginSuccessEvent;
import com.qianfeng.smartdevice.mapper.LogininforMapper;
import com.qianfeng.smartdevice.mapper.UserOnlineMapper;
import com.qianfeng.smartdevice.pojo.Logininfor;
import com.qianfeng.smartdevice.pojo.MyBaseUser;
import com.qianfeng.smartdevice.pojo.User;
import com.qianfeng.smartdevice.pojo.UserOnline;
import com.qianfeng.smartdevice.service.UserService;
import com.qianfeng.smartdevice.utils.RequestUtils;
import com.qianfeng.smartdevice.utils.SecruitUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * Created by Jackiechan on 2022/1/5/20:22
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@Component
public class LoginEventListener {


    private LogininforMapper logininforMapper;

    private UserService userService;

    private UserOnlineMapper userOnlineMapper;

    @Autowired
    public void setUserOnlineMapper(UserOnlineMapper userOnlineMapper) {
        this.userOnlineMapper = userOnlineMapper;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setLogininforMapper(LogininforMapper logininforMapper) {
        this.logininforMapper = logininforMapper;
    }

    @EventListener
    public void onEvent(UserLoginSuccessEvent event) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        MyBaseUser user = SecruitUtils.getUser();
        Map<String, String> osAndBrowserInfo = RequestUtils.getOsAndBrowserInfo(request);//浏览器和系统信息
        String ip = RequestUtils.getRemoteHost(request);

        CompletableFuture.runAsync(()->{
            String location = RequestUtils.getLocationByIp(ip);//根据ip获取到位置,这个操作比较消耗时间,可以每次都执行一下
            Logininfor logininfor = new Logininfor();
            logininfor.setLoginLocation(location);
            logininfor.setLoginName(user.getUsername());
            logininfor.setLoginTime(new Date());
            logininfor.setBrowser(osAndBrowserInfo.get("browser"));
            logininfor.setOs(osAndBrowserInfo.get("os"));
            logininfor.setMsg("登陆成功");
            logininfor.setStatus("1");
            logininfor.setIpaddr(ip);
            logininforMapper.addLoginLog(logininfor);
        });

        CompletableFuture.runAsync(()->{
            userService.updateLogin(user.getUsername(),new Date(),ip);
        });

        CompletableFuture.runAsync(()->{
            String sessionId = request.getSession().getId();
            UserOnline userOnline = new UserOnline();
            userOnline.setSessionId(sessionId);
            userOnline.setBrowser(osAndBrowserInfo.get("browser"));
            userOnline.setOs(osAndBrowserInfo.get("os"));
            userOnline.setIpaddr(ip);
            String location = RequestUtils.getLocationByIp(ip);//根据ip获取到位置,这个操作比较消耗时间,可以每次都执行一下
            userOnline.setLoginLocation(location);
            userOnline.setStatus("1");
            userOnline.setLoginName(user.getUsername());
            userOnline.setExpireTime(30L);
            userOnline.setStartTimestamp(new Date());
            userOnlineMapper.deleteByUsername(user.getUsername());
            userOnlineMapper.addOnline(userOnline);
        });
    }

    @EventListener
    public void onEvent(UserLoginFailEvent event) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Map<String, String> osAndBrowserInfo = RequestUtils.getOsAndBrowserInfo(request);//浏览器和系统信息
        String ip = RequestUtils.getRemoteHost(request);

        CompletableFuture.runAsync(()->{
            String location = RequestUtils.getLocationByIp(ip);//根据ip获取到位置,这个操作比较消耗时间,可以每次都执行一下
            Logininfor logininfor = new Logininfor();
            logininfor.setLoginLocation(location);
            logininfor.setLoginName(event.getUserName());
            logininfor.setLoginTime(new Date());
            logininfor.setBrowser(osAndBrowserInfo.get("browser"));
            logininfor.setOs(osAndBrowserInfo.get("os"));
            logininfor.setMsg("用户名密码错误");
            logininfor.setStatus("0");
            logininfor.setIpaddr(ip);
            logininforMapper.addLoginLog(logininfor);
        });
    }


}
